//
// DotNetNuke - http://www.dotnetnuke.com
// Copyright (c) 2002-2010
// by Perpetual Motion Interactive Systems Inc. ( http://www.perpetualmotion.ca )
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated 
// documentation files (the "Software"), to deal in the Software without restriction, including without limitation 
// the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and 
// to permit persons to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or substantial portions 
// of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED 
// TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL 
// THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF 
// CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER 
// DEALINGS IN THE SOFTWARE.
//

using System;
using System.Collections;
using System.IO;
using System.Web;
using System.Web.UI.WebControls;
using DotNetNuke.Common.Utilities;
using DotNetNuke.Entities.Modules;
using DotNetNuke.Services.FileSystem;
using DotNetNuke.Services.Localization;
using DotNetNuke.UI.Skins;
namespace DotNetNuke.Modules.Admin.FileManager
{
	partial class WebUpload : DotNetNuke.Entities.Modules.PortalModuleBase
	{
		private string _FileTypeName;
		private UploadType _FileType;
		private string _DestinationFolder;
		private string _UploadRoles;
		private string _RootFolder;
		public string DestinationFolder
		{
			get
			{
				if (_DestinationFolder == null)
				{
					_DestinationFolder = string.Empty;
					if ((Request.QueryString["dest"] != null))
					{
						_DestinationFolder = Common.Globals.QueryStringDecode(Request.QueryString["dest"]);
					}
				}
				return FileSystemUtils.RemoveTrailingSlash(_DestinationFolder.Replace("\\", "/"));
			}
		}
		public UploadType FileType
		{
			get
			{
				_FileType = UploadType.File;
				if ((Request.QueryString["ftype"] != null))
				{
					switch (Request.QueryString["ftype"].ToLower())
					{
						case "file":
						case "container":
						case "skin":
							_FileType = (UploadType)System.Enum.Parse(typeof(UploadType), Request.QueryString["ftype"]);
							break;
					}
				}
				return _FileType;
			}
		}
		public string FileTypeName
		{
			get
			{
				if (_FileTypeName == null)
				{
					_FileTypeName = Localization.GetString(FileType.ToString(), this.LocalResourceFile);
				}
				return _FileTypeName;
			}
		}
		public int FolderPortalID
		{
			get
			{
				if (IsHostMenu)
				{
					return Null.NullInteger;
				}
				else
				{
					return PortalId;
				}
			}
		}
		public string RootFolder
		{
			get
			{
				if (_RootFolder == null)
				{
					if (IsHostMenu)
					{
						_RootFolder = Common.Globals.HostMapPath;
					}
					else
					{
						_RootFolder = PortalSettings.HomeDirectoryMapPath;
					}
				}
				return _RootFolder;
			}
		}
		public string UploadRoles
		{
			get
			{
				if (_UploadRoles == null)
				{
					_UploadRoles = string.Empty;
					ModuleController objModules = new ModuleController();
					ModuleInfo ModInfo;
					if (IsHostMenu)
					{
						ModInfo = objModules.GetModuleByDefinition(Null.NullInteger, "File Manager");
					}
					else
					{
						ModInfo = objModules.GetModuleByDefinition(PortalId, "File Manager");
					}
					Hashtable settings = new ModuleController().GetModuleSettings(ModInfo.ModuleID);
					if (Convert.ToString(settings["uploadroles"]) != null)
					{
						_UploadRoles = Convert.ToString(settings["uploadroles"]);
					}
				}
				return _UploadRoles;
			}
		}
		private void CheckSecurity()
		{
			if (!IsEditable)
			{
				Response.Redirect(Common.Globals.NavigateURL("Access Denied"), true);
			}
		}
		private void LoadFolders()
		{
			ddlFolders.Items.Clear();
			ArrayList folders = FileSystemUtils.GetFoldersByUser(FolderPortalID, true, true, "ADD");
			foreach (FolderInfo folder in folders)
			{
				ListItem FolderItem = new ListItem();
				if (folder.FolderPath == Null.NullString)
				{
					if (IsHostMenu)
					{
						FolderItem.Text = Localization.GetString("HostRoot", this.LocalResourceFile);
					}
					else
					{
						FolderItem.Text = Localization.GetString("PortalRoot", this.LocalResourceFile);
					}
				}
				else
				{
					FolderItem.Text = FileSystemUtils.RemoveTrailingSlash(folder.DisplayPath);
				}
				FolderItem.Value = folder.FolderPath;
				ddlFolders.Items.Add(FolderItem);
			}
			if (!String.IsNullOrEmpty(DestinationFolder))
			{
				if (ddlFolders.Items.FindByText(DestinationFolder) != null)
				{
					ddlFolders.Items.FindByText(DestinationFolder).Selected = true;
				}
			}
		}
		public string ReturnURL()
		{
			int TabID = PortalSettings.HomeTabId;
			if (Request.Params["rtab"] != null)
			{
				TabID = int.Parse(Request.Params["rtab"]);
			}
			return Common.Globals.NavigateURL(TabID);
		}
		protected override void OnInit(EventArgs e)
		{
			base.OnInit(e);

			this.ModuleConfiguration.ModuleTitle = Services.Localization.Localization.GetString("UploadType" + FileType.ToString(), this.LocalResourceFile);
		}
		protected override void OnLoad(EventArgs e)
		{
			base.OnLoad(e);

			cmdAdd.Click += new EventHandler(cmdAdd_Click);
			cmdReturn1.Click += new EventHandler(cmdReturn_Click);
			cmdReturn2.Click += new EventHandler(cmdReturn_Click);

			try
			{
				CheckSecurity();
				string strHost = Localization.GetString("HostRoot", this.LocalResourceFile);
				string strPortal = Localization.GetString("PortalRoot", this.LocalResourceFile);
				if (!Page.IsPostBack)
				{
					cmdAdd.Text = Services.Localization.Localization.GetString("UploadType" + FileType.ToString(), this.LocalResourceFile);
					if (FileType == UploadType.File)
					{
						trFolders.Visible = true;
						trRoot.Visible = true;
						trUnzip.Visible = true;
						if (IsHostMenu)
						{
							lblRootType.Text = strHost + ":";
							lblRootFolder.Text = RootFolder;
						}
						else
						{
							lblRootType.Text = strPortal + ":";
							lblRootFolder.Text = RootFolder;
						}
						LoadFolders();
					}
					chkUnzip.Checked = false;
				}
			}
			catch (Exception exc)
			{
				Services.Exceptions.Exceptions.ProcessModuleLoadException(this, exc);
			}
		}
		private void cmdAdd_Click(object sender, System.EventArgs e)
		{
			try
			{
				CheckSecurity();
				string strFileName;
				string strExtension = "";
				string strMessage = "";
				HttpPostedFile postedFile = cmdBrowse.PostedFile;
				string strInvalid = Services.Localization.Localization.GetString("InvalidExt", this.LocalResourceFile);
				strFileName = System.IO.Path.GetFileName(postedFile.FileName);
				strExtension = Path.GetExtension(strFileName);
				if (!String.IsNullOrEmpty(postedFile.FileName))
				{
					switch (FileType)
					{
						case UploadType.File:
							strMessage += FileSystemUtils.UploadFile(RootFolder + ddlFolders.SelectedItem.Value.Replace("/", "\\"), postedFile, chkUnzip.Checked);
							break;
						case UploadType.Skin:
							if (strExtension.ToLower() == ".zip")
							{
								UI.Skins.SkinController objSkins = new UI.Skins.SkinController();
								Label objLbl = new Label();
								objLbl.CssClass = "Normal";
								objLbl.Text = DotNetNuke.UI.Skins.SkinController.UploadLegacySkin(RootFolder, SkinController.RootSkin, Path.GetFileNameWithoutExtension(postedFile.FileName), postedFile.InputStream);
								phPaLogs.Controls.Add(objLbl);
							}
							else
							{
								strMessage += strInvalid + " " + FileTypeName + " " + strFileName;
							}
							break;
						case UploadType.Container:
							if (strExtension.ToLower() == ".zip")
							{
								UI.Skins.SkinController objSkins = new UI.Skins.SkinController();
								Label objLbl = new Label();
								objLbl.CssClass = "Normal";
								objLbl.Text = DotNetNuke.UI.Skins.SkinController.UploadLegacySkin(RootFolder, SkinController.RootContainer, Path.GetFileNameWithoutExtension(postedFile.FileName), postedFile.InputStream);
								phPaLogs.Controls.Add(objLbl);
							}
							else
							{
								strMessage += strInvalid + " " + FileTypeName + " " + strFileName;
							}
							break;
					}
				}
				else
				{
					strMessage = Services.Localization.Localization.GetString("NoFile", this.LocalResourceFile);
				}
				if (phPaLogs.Controls.Count > 0)
				{
					tblLogs.Visible = true;
				}
				else if (String.IsNullOrEmpty(strMessage))
				{
				    DotNetNuke.UI.Skins.Skin.AddModuleMessage(this,
				                                              String.Format(
				                                                  Localization.GetString("FileUploadSuccess", this.LocalResourceFile),
				                                                  strFileName),
				                                              DotNetNuke.UI.Skins.Controls.ModuleMessage.ModuleMessageType.GreenSuccess);
				}
				else
				{
					lblMessage.Text = strMessage;
				}
			}
			catch (Exception exc)
			{
				Services.Exceptions.Exceptions.ProcessModuleLoadException(this, exc);
			}
		}
		private void cmdReturn_Click(System.Object sender, System.EventArgs e)
		{
			Response.Redirect(ReturnURL(), true);
		}
	}
}
